package cn.schoolwow.quickapi.module.initial.flow;

import cn.schoolwow.quickapi.domain.QuickAPIOption;
import cn.schoolwow.quickapi.module.common.domain.APIDocument;
import cn.schoolwow.quickapi.module.common.domain.APIEntity;
import cn.schoolwow.quickapi.module.common.domain.APIField;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;

public class ExecuteQuickAPIListenerFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        executeAPIEntityListener(flowContext);
        executeAPIFieldListener(flowContext);
    }

    @Override
    public String name() {
        return "执行QuickAPI中用户指定的监听器";
    }

    private void executeAPIEntityListener(FlowContext flowContext){
        QuickAPIOption quickAPIOption = flowContext.checkInstanceData(QuickAPIOption.class);

        if(null==quickAPIOption.apiEntityListener){
            return;
        }
        APIDocument apiDocument = flowContext.checkInstanceData(APIDocument.class);
        for(APIEntity apiEntity:apiDocument.apiEntityMap.values()){
            quickAPIOption.apiEntityListener.handleAPIEntity(apiEntity);
        }
    }

    private void executeAPIFieldListener(FlowContext flowContext){
        QuickAPIOption quickAPIOption = flowContext.checkInstanceData(QuickAPIOption.class);

        if(null==quickAPIOption.apiFieldListener){
            return;
        }
        APIDocument apiDocument = flowContext.checkInstanceData(APIDocument.class);
        for(APIEntity apiEntity:apiDocument.apiEntityMap.values()){
            for(APIField apiField:apiEntity.apiFieldList){
                quickAPIOption.apiFieldListener.handleAPIEntity(apiField);
            }
        }
    }
}
